<template>
  <div class="attendance-container">
    <div class="card">
      <h3>员工考勤</h3>
      
      <!-- 显示当前登录用户信息 -->
      <div v-if="currentUser" class="user-info">
        <p><strong>当前用户：</strong>{{ currentUser.empName }}</p>
        <p><strong>员工ID：</strong>{{ currentUser.empId }}</p>
        <p><strong>部门：</strong>{{ currentUser.deptId }}</p>
      </div>
      
      <!-- 显示考勤状态 -->
      <div v-if="attendanceStatus" class="status-info">
        <p><strong>签到时间：</strong>{{ formatTime(attendanceStatus.checkInTime) || '未签到' }}</p>
        <p><strong>签退时间：</strong>{{ formatTime(attendanceStatus.checkOutTime) || '未签退' }}</p>
        <p><strong>状态：</strong>
          {{ 
            attendanceStatus.checkInTime && attendanceStatus.checkOutTime ? '已签到并签退' :
            attendanceStatus.checkInTime ? '已签到' :
            '未签到'
          }}
        </p>
      </div>

      <div class="button-group">
        <button @click="checkIn" :disabled="loading || isAlreadyCheckedIn">
          {{ loading ? '正在签到...' : (isAlreadyCheckedIn ? '已签到' : '签到') }}
        </button>
        <button @click="checkOut" :disabled="loading || !isAlreadyCheckedIn || isAlreadyCheckedOut">
          {{ loading ? '正在签退...' : (isAlreadyCheckedOut ? '已签退' : '签退') }}
        </button>
        <button @click="checkStatus" :disabled="loading">
          {{ loading ? '正在查询...' : '刷新状态' }}
        </button>
      </div>

      <div v-if="message" class="message">{{ message }}</div>
    </div>
  </div>
</template>

<script>
import { useAuthStore } from "@/stores/auth";
import { useGlobalStore, axios } from "@/stores/index";

export default {
  name: 'Attendance',
  data() {
    return {
      currentEmpId: null,
      currentUser: null,
      loading: false,
      message: '',
      attendanceStatus: null,
      isAlreadyCheckedIn: false,
      isAlreadyCheckedOut: false,
      currentDate: null,  // 新增：记录当前日期
      resetTimer: null    // 新增：存储定时器引用
    };
  },
  mounted() {
    this.currentDate = this.getCurrentDate();
    this.initAttendance();
    this.setupDailyReset();  // 新增：设置每日重置
  },
  beforeUnmount() {
    // 新增：清理定时器
    if (this.resetTimer) {
      clearTimeout(this.resetTimer);
      this.resetTimer = null;
    }
  },
  methods: {
    // 获取标准格式的当前日期 (YYYY-MM-DD)
    getCurrentDate() {
      const date = new Date();
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    
    // 设置每日重置机制
    setupDailyReset() {
      // 清理旧定时器
      if (this.resetTimer) {
        clearTimeout(this.resetTimer);
      }
      
      // 计算到午夜的时间
      const now = new Date();
      const midnight = new Date(now);
      midnight.setHours(24, 0, 0, 0);
      const timeUntilMidnight = midnight - now;
      
      // 设置定时器
      this.resetTimer = setTimeout(() => {
        this.resetDailyStatus();
        // 每天重置一次
        this.resetTimer = setInterval(() => {
          this.resetDailyStatus();
        }, 24 * 60 * 60 * 1000);
      }, timeUntilMidnight);
    },
    
    // 重置每日考勤状态
    resetDailyStatus() {
      const today = this.getCurrentDate();
      if (this.currentDate !== today) {
        this.currentDate = today;
        this.attendanceStatus = null;
        this.isAlreadyCheckedIn = false;
        this.isAlreadyCheckedOut = false;
        console.log('已重置今日考勤状态');
        this.message = '已进入新工作日，请签到';
        this.checkStatus(); // 重新获取状态
      }
    },
    
    // 初始化考勤组件
    async initAttendance() {
      try {
        this.loading = true;
        
        // 1. 获取当前登录ID
        const authStore = useAuthStore();
        const loginId = authStore.currentLoginId;
        
        console.log("当前登录ID:", loginId);
        if (!loginId) {
          throw new Error("未检测到登录信息，请重新登录");
        }
        
        // 2. 通过 loginId 获取 empId
        let empId;
        try {
          const response = await axios.get(`/user/getEmpId`, {
            params: { loginId }
          });
          
          // 处理标准响应格式 { code: 200, data: empId }
          if (response && response.code === 200) {
            empId = response.data;
          } 
          // 处理直接返回 empId 的情况
          else if (typeof response === 'number' || typeof response === 'string') {
            empId = response;
          } 
          // 处理可能的其他响应格式
          else if (response && response.empId) {
            empId = response.empId;
          } else {
            throw new Error(response.message || "获取员工ID失败");
          }
          
          console.log("获取到的员工ID:", empId);
        } catch (error) {
          console.error("获取empId失败:", error);
          // 尝试从错误响应中提取 empId
          if (error.response && error.response.data) {
            if (error.response.data.code === 200) {
              empId = error.response.data.data;
            } else if (typeof error.response.data === 'number' || typeof error.response.data === 'string') {
              empId = error.response.data;
            }
          }
          
          if (!empId) {
            throw error;
          }
        }
        
        this.currentEmpId = empId;
        
        // 3. 获取用户基本信息
        let userResponse;
        try {
          userResponse = await axios.get(`/userManage/${this.currentEmpId}`);
          
          // 处理标准响应格式
          if (userResponse && userResponse.code === 200 && userResponse.data) {
            this.currentUser = userResponse.data;
          } 
          // 处理直接返回数据的情况
          else if (userResponse && userResponse.empId) {
            this.currentUser = userResponse;
          } else {
            throw new Error(userResponse.message || "用户信息格式异常");
          }
        } catch (error) {
          console.error("获取用户基本信息失败:", error);
          this.currentUser = {
            empId: this.currentEmpId,
            empName: "未知用户",
            deptId: "未知部门"
          };
        }
        
        // 4. 检查当前考勤状态
        await this.checkStatus();
      } catch (error) {
        console.error("初始化考勤失败:", error);
        this.message = error.message || '初始化考勤失败，请重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 格式化时间显示
    formatTime(dateTimeString) {
      if (!dateTimeString) return null;
      
      try {
        // 处理 ISO 8601 格式时间字符串
        const date = new Date(dateTimeString);
        if (isNaN(date)) {
          return dateTimeString; // 如果日期无效，返回原始字符串
        }
        
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      } catch (e) {
        console.error("时间格式化失败:", e);
        return dateTimeString;
      }
    },
    
    // 检查当前考勤状态
    async checkStatus() {
      // 新增：检查日期是否变更
      const today = this.getCurrentDate();
      if (this.currentDate !== today) {
        this.currentDate = today;
        this.attendanceStatus = null;
        this.isAlreadyCheckedIn = false;
        this.isAlreadyCheckedOut = false;
      }
      
      if (!this.currentEmpId) {
        this.message = '员工ID未获取到，请重新登录';
        return;
      }

      this.loading = true;
      this.attendanceStatus = null;

      try {
        const response = await axios.get(`/attendance/today/${this.currentEmpId}`);
        
        // 处理标准响应格式
        if (response && response.code === 200 && response.data) {
          this.attendanceStatus = response.data;
          this.isAlreadyCheckedIn = !!response.data.checkInTime;
          this.isAlreadyCheckedOut = !!response.data.checkOutTime;
          this.message = '状态查询成功！';
        } 
        // 处理直接返回数据的情况
        else if (response && response.checkInTime !== undefined) {
          this.attendanceStatus = response;
          this.isAlreadyCheckedIn = !!response.checkInTime;
          this.isAlreadyCheckedOut = !!response.checkOutTime;
          this.message = '状态查询成功！';
        } else {
          this.message = response?.message || '状态数据异常';
        }
      } catch (error) {
        console.error("状态查询失败:", error);
        // 更详细的错误信息
        this.message = error.response?.data?.message || 
                      error.message || 
                      '状态查询失败，请检查网络';
      } finally {
        this.loading = false;
      }
    },
    
    // 签到
    async checkIn() {
      if (!this.currentEmpId) {
        this.message = '员工ID未获取到，请重新登录';
        return;
      }

      if (this.isAlreadyCheckedIn) {
        this.message = '您今天已经签到过了！';
        return;
      }

      this.loading = true;
      this.message = '';

      try {
        // 修复关键点：使用 URLSearchParams 构建表单数据
        const formData = new URLSearchParams();
        formData.append('empId', this.currentEmpId);
        
        const response = await axios.post(`/attendance/checkIn`, formData, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        // 处理标准响应格式
        if (response && response.code === 200 && response.data) {
          this.message = '签到成功！';
          this.isAlreadyCheckedIn = true;
          
          // 更新考勤状态
          this.attendanceStatus = {
            ...this.attendanceStatus,
            checkInTime: response.data.checkInTime
          };
          
          // 本地缓存签到状态 - 使用标准日期格式
          const today = this.getCurrentDate();
          localStorage.setItem(`checkedIn_${this.currentEmpId}_${today}`, 'true');
          
          // 刷新状态
          await this.checkStatus();
        } 
        // 处理直接返回数据的情况
        else if (response && response.checkInTime) {
          this.message = '签到成功！';
          this.isAlreadyCheckedIn = true;
          
          // 更新考勤状态
          this.attendanceStatus = {
            ...this.attendanceStatus,
            checkInTime: response.checkInTime
          };
          
          // 本地缓存签到状态 - 使用标准日期格式
          const today = this.getCurrentDate();
          localStorage.setItem(`checkedIn_${this.currentEmpId}_${today}`, 'true');
          
          // 刷新状态
          await this.checkStatus();
        } else {
          this.message = response?.message || '签到失败，请检查网络';
        }
      } catch (error) {
        console.error("签到失败:", error);
        this.message = error.response?.data?.message || 
                      error.message || 
                      '签到失败，请检查网络';
      } finally {
        this.loading = false;
      }
    },
    
    // 签退
    async checkOut() {
      if (!this.currentEmpId) {
        this.message = '员工ID未获取到，请重新登录';
        return;
      }

      if (!this.isAlreadyCheckedIn) {
        this.message = '请先签到后再进行签退';
        return;
      }
      
      if (this.isAlreadyCheckedOut) {
        this.message = '您今天已经签退过了！';
        return;
      }

      this.loading = true;
      this.message = '';

      try {
        // 修复关键点：使用 URLSearchParams 构建表单数据
        const formData = new URLSearchParams();
        formData.append('empId', this.currentEmpId);
        
        const response = await axios.post(`/attendance/checkOut`, formData, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        // 处理标准响应格式
        if (response && response.code === 200 && response.data) {
          this.message = '签退成功！';
          this.isAlreadyCheckedOut = true;
          
          // 更新考勤状态
          this.attendanceStatus = {
            ...this.attendanceStatus,
            checkOutTime: response.data.checkOutTime
          };
          
          // 本地缓存签退状态 - 使用标准日期格式
          const today = this.getCurrentDate();
          localStorage.setItem(`checkedOut_${this.currentEmpId}_${today}`, 'true');
          
          // 刷新状态
          await this.checkStatus();
        } 
        // 处理直接返回数据的情况
        else if (response && response.checkOutTime) {
          this.message = '签退成功！';
          this.isAlreadyCheckedOut = true;
          
          // 更新考勤状态
          this.attendanceStatus = {
            ...this.attendanceStatus,
            checkOutTime: response.checkOutTime
          };
          
          // 本地缓存签退状态 - 使用标准日期格式
          const today = this.getCurrentDate();
          localStorage.setItem(`checkedOut_${this.currentEmpId}_${today}`, 'true');
          
          // 刷新状态
          await this.checkStatus();
        } else {
          this.message = response?.message || '签退失败，请检查网络';
        }
      } catch (error) {
        console.error("签退失败:", error);
        this.message = error.response?.data?.message || 
                      error.message || 
                      '签退失败，请检查网络';
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.attendance-container {
  padding: 20px;
  max-width: 500px;
  margin: 50px auto;
  background-color: #f9f9f9;
}

.card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 30px;
  border: 1px solid #e0e0e0;
}

.user-info {
  background-color: #e6f7ff;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
  font-size: 14px;
  line-height: 1.6;
}

.user-info p {
  margin: 5px 0;
}

.status-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
  font-size: 14px;
  line-height: 1.6;
}

.status-info p {
  margin: 5px 0;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s ease;
  flex: 1;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
  opacity: 0.7;
}

button:nth-child(1) {
  background-color: #1890ff;
  color: white;
}

button:nth-child(2) {
  background-color: #fa8c16;
  color: white;
}

button:nth-child(3) {
  background-color: #f5f5f5;
  color: #333;
}

.message {
  color: #e74c3c;
  font-size: 14px;
  margin-top: 10px;
}
</style>